<?php
/* 解析列表定义规则*/
function get_list_field($data, $grid)
{
    // 获取当前字段数据
    foreach ($grid['field'] as $field) {
        $array = explode('|', $field);
        $temp = $data[$array[0]];
        // 函数支持
        if (isset($array[1])) {
            $temp = call_user_func($array[1], $temp);
        }
        $data2[$array[0]] = $temp;
    }
    if (!empty($grid['format'])) {
        $value = preg_replace_callback('/\[([a-z_]+)\]/', function ($match) use ($data2) {
            return $data2[$match[1]];
        }, $grid['format']);
    } else {
        $value = implode(' ', $data2);
    }

    // 链接支持
    if ('title' == $grid['field'][0] && '目录' == $data['type']) {
        // 目录类型自动设置子文档列表链接
        $grid['href'] = '[LIST]';
    }
    if (!empty($grid['href'])) {
        $links = explode(',', $grid['href']);
        foreach ($links as $link) {
            $array = explode('|', $link);
            $href = $array[0];
            if (preg_match('/^\[([a-z_]+)\]$/', $href, $matches)) {
                $val[] = $data2[$matches[1]];
            } else {
                $show = isset($array[1]) ? $array[1] : $value;
                // 替换系统特殊字符串
                $href = str_replace(
                    array('[DELETE]', '[EDIT]', '[LIST]'),
                    array('setstatus?status=-1&ids=[id]',
                        'edit?id=[id]&model=[model_id]&cate_id=[category_id]',
                        'index?pid=[id]&model=[model_id]&cate_id=[category_id]'),
                    $href);

                // 替换数据变量
                $href = preg_replace_callback('/\[([a-z_]+)\]/', function ($match) use ($data) {
                    return $data[$match[1]];
                }, $href);

                $val[] = '<a href="' . url($href) . '">' . $show . '</a>';
            }
        }
        $value = implode(' ', $val);
    }
    return $value;
}

// 获取属性类型信息
function get_attribute_type($type = '')
{
    // TODO 可以加入系统配置
    static $_type = array(
        'num' => array('数字', 'int(10) UNSIGNED NOT NULL'),
        'string' => array('字符串', 'varchar(255) NOT NULL'),
        'textarea' => array('文本框', 'text NOT NULL'),
        'date' => array('日期', 'int(10) NOT NULL'),
        'datetime' => array('时间', 'int(10) NOT NULL'),
        'bool' => array('布尔', 'tinyint(2) NOT NULL'),
        'select' => array('枚举', 'char(50) NOT NULL'),
        'radio' => array('单选', 'char(10) NOT NULL'),
        'checkbox' => array('多选', 'varchar(100) NOT NULL'),
        'editor' => array('编辑器', 'text NOT NULL'),
        'picture' => array('上传图片', 'int(10) UNSIGNED NOT NULL'),
        'file' => array('上传附件', 'int(10) UNSIGNED NOT NULL'),
    );
    return $type ? $_type[$type][0] : $_type;
}

/**
 * 权限验证
 * @param null $name
 * @param null $path
 * @param string $relation
 * @return bool
 */
function auth_check($name = null, $path = null, $relation = 'or')
{
    if ($path) {
        $name = strtolower($path . $name);
    } else {
        $request = request();
        $module = $request->module();
        $controller = $request->controller();
        $name = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $module . "/" . $controller . "/" . $name));
    }

    return cmf_auth_check(cmf_get_current_admin_id(), $name, $relation);
}

/**
 * 获取所有部门id
 * @param $gids
 * @param bool $flag
 * @return array|string
 */
function getGroups($gids, $flag = true)
{
    is_array($gids) && $gids = implode(',', $gids);
    $ids = db('department')->where([
        'parent_id' => [
            'in', $gids
        ]
    ])->column('id');

    if (!$ids) {
        if ($flag) {
            return $gids;
        } else {
            return '';
        }
    }
    $ids = implode(',', $ids);

    $id = getGroups($ids, false);
    if ($id) {
        $ids = $ids . ',' . $id;
    }

    if ($flag) {
        return $gids . ',' . $ids;
    } else {
        return $ids;
    }
}

/**
 * 获取用户
 * @param $gids
 * @return string
 */
function getUsers($gids)
{
    is_array($gids) && $gids = implode(',', $gids);
    $users = db('department_user')->where([
        'dep_id' => [
            'in', $gids
        ]
    ])->column('user_id');
    return implode(',', $users);
}

/**
 * 不验证方法
 * @return bool
 */
function auth_public()
{
    $request = request();
    $public = [
        'select',
        'check',
    ];
    if (in_array($request->action(), $public)) {
        return true;
    }
    return false;
}

/**
 * 用户所属部门
 * @param $uid
 * @return array
 */
function get_user_group($uid)
{
    return db('department_user')->where([
        'user_id' => $uid
    ])->column('dep_id');
}

/**
 * 获取当前用户所有部门id
 * @return array|string
 */
function get_departments()
{
    $admin_id = cmf_get_current_admin_id();
    if($admin_id != 1) {
        return getUsersGroup($admin_id);
    }
    return '';
}

/**
 * 获取部门管理权限
 * @param $role_id
 * @return array
 */
function get_show_department($role_id)
{
    $result = db('role')
        ->alias('role')
        ->join('__ROLE_DEPARTMENT__ role_department','role.id = role_department.role_id','left')
        ->where(['role.id' => ['in',$role_id]])
        ->field('role.department_id as id,show_department,company_manage')
        ->select();
    return $result;
}

/**
 * 获取属性权限
 * @param $role_id
 * @return array
 */
function get_role_department($role_id,$field)
{
    $result = db('role')
        ->alias('role')
        ->join('__ROLE_DEPARTMENT__ role_department','role.id = role_department.role_id','left')
        ->where(['role.id' => ['in',$role_id]])
        ->field('role.id,'.$field)
        ->select();
    return $result;
}

/**
 * @return array|string
 */
function get_access_user($uid = 0)
{
    if(!$uid) {
        $uid = cmf_get_current_admin_id();
    }
    if(!$uid) {
        return false;
    }
    if ($uid != 1) {
        $users = implode(',', getUsersForRole($uid));
        return $users;
    }
    return '';
}

function strstar($str){
    $str = trim($str);
    $len = mb_strlen($str);
    $star = '';
    for ($i = 0;$i < $len;$i++) {
        $star .= '*';
    }
    if($len > 4) {
        return mb_substr($str,0,2) . $star . mb_substr($str,-2);
    }else{
        return $str;
    }
}

/**
 * 获取所有父级分类
 * @param $id
 * @param array $fields
 */
function getParent($table,$id, $fields = ['id'])
{
    $name = db($table)->getTable();
    foreach ($fields as &$field) {
        if ($field != 'lvl') {
            $field = 't1.' . $field;
        }
    }
    $fields = implode(',', $fields);
    $sql = "select $fields from {$name} t1 join (select @r as _id,(select @r := parent_id from {$name} where id = _id) as parent_id,@l := @l + 1 AS lvl from (select @r := {$id},@l := 0) vars,{$name} where @r <> 0) t2 on t1.id = t2._id order by t2.lvl";
    return db()->query($sql);
}

function getUserInfo($uid) {
    return db('user')->find($uid);
}

/**
 * @param $uid
 * @return array
 */
function getUsersForRole($uid) {
    $roles = db('role_user')
        ->where(['user_id' => $uid])
        ->column('role_id');

    $role_deps = get_show_department($roles);
    $users = [];
    foreach ($role_deps as $role_dep) {
        if($role_dep['company_manage']) {
            $department = get_user_group($uid);
            $departments = getParent('department',$department[0],['id','lvl','is_company']);
            $parent = [];
            foreach ($departments as $department) {
                if($department['is_company']) {
                    $parent = $department;
                    break;
                }
            }
            $gids = getGroups($parent['id']);
            $users[] = getUsers($gids);
        }elseif ($role_dep['show_department']) {
            $gids = getGroups($role_dep['id']);
            $users[] = getUsers($gids);
        } else {
            $users[] = $uid;
        }
    }
    return $users;
}

function getUsersGroup($uid) {
    $roles = db('role_user')
        ->where(['user_id' => $uid])
        ->column('role_id');

    $role_deps = get_show_department($roles);
    $gids = '';
    foreach ($role_deps as $role_dep) {
        if($role_dep['company_manage']) {
            $department = get_user_group($uid);
            $departments = getParent('department',$department[0],['id','lvl','is_company']);
            $parent = [];
            foreach ($departments as $department) {
                if($department['is_company']) {
                    $parent = $department;
                    break;
                }
            }
            $gid = getGroups($parent['id']);
            if($gids) {
                $gids .= ',';
            }
            $gids .= $gid;
        }else{
            $gid = getGroups($role_dep['id']);
            if($gids) {
                $gids .= ',';
            }
            $gids .= $gid;
        }
    }
    return $gids;
}